<template>
  <div class="flex-d-col h-100%">
    <breadcrumb />
    <div class="app-main-container h-100% flex">
      <div class="left flex-d-col w-50%">
        <div class="title">
          <!-- 题目详情 -->
          <el-button plain size="small" class="pl-4px pr-4px ml-10px h-18px" @click="back"
            >返回</el-button
          >
        </div>
        <div class="flex h-100% p-30px of-y-overlay">
          <el-form :model="formData" class="w-100%" label-width="6em">
            <el-form-item label="规章名称">
              <span>{{ formData.name }}</span>
              <el-button type="primary" link class="ml-10px" @click="btnRename"
                >重命名</el-button
              >
            </el-form-item>
            <el-divider />
            <el-form-item>
              <el-button type="primary" size="small" @click="publishNew"
                >上传新版本</el-button
              >
            </el-form-item>
            <el-form-item label="版本记录">
              <el-table
                :data="tableData.data"
                stripe
                header-cell-class-name="table-header"
                style="width: 100%"
              >
                <el-table-column prop="publishTime" label="发布时间" width="100">
                </el-table-column>
                <el-table-column prop="file.fileName" label="文件名"> </el-table-column>
                <el-table-column prop="date" label="状态" width="80">
                  <template #default="scope">
                    <el-text :type="scope.row.isActive ? 'success' : 'info'">{{
                      scope.row.isActive ? "启用" : "停用"
                    }}</el-text>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="180">
                  <template #default="scope">
                    <div class="flex">
                      <el-button
                        type="primary"
                        size="small"
                        link
                        @click="showRight(scope.row, 1)"
                        >预览</el-button
                      >
                      <el-button
                        type="primary"
                        size="small"
                        link
                        @click="showRight(scope.row, 2)"
                        >查看题目</el-button
                      >

                      <el-dropdown class="ml-10px">
                        <el-button type="primary" size="small" link>
                          更多
                          <el-icon class="el-icon--right">
                            <arrow-down />
                          </el-icon>
                        </el-button>

                        <template #dropdown>
                          <el-dropdown-menu>
                            <el-dropdown-item @click="down(scope.row)"
                              >下载文件</el-dropdown-item
                            >
                            <!-- <el-dropdown-item @click="del(scope.row)"
                              >删除</el-dropdown-item
                            > -->
                            <el-dropdown-item @click="changeState(scope.row)"
                              >更改状态</el-dropdown-item
                            >
                          </el-dropdown-menu>
                        </template>
                      </el-dropdown>
                    </div>
                  </template>
                </el-table-column>
              </el-table>
              <div class="w-100%">
                <el-pagination
                  class="flex-x-center mt-10px"
                  small
                  layout="prev, pager, next"
                  v-model:current-page="page.index"
                  :page-size="page.size"
                  :total="page.total"
                  hide-on-single-page
                  @current-change="pageChange"
                />
              </div>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div class="right flex-d-col flex-1 ml-20px">
        <div class="title">&nbsp;</div>
        <div class="flex-d-col h-100%">
          <!-- <iframe :src="pdf" frameborder="0" height="100%" width="100%"></iframe> -->
          <vue-pdf-app v-if="rightShow == 1" style="height: 100%" :pdf="pdf" />
          <template v-else-if="rightShow == 2">
            <theoryList :data="acData"></theoryList>
          </template>
        </div>
      </div>
    </div>
    <el-dialog
      v-model="addEditVisible.show"
      :title="addEditVisible.title"
      width="600"
      @close="addEditClose"
    >
      <el-form
        :key="addEditVisible.show"
        ref="RefForm"
        :model="addEditVisible.data"
        label-width="120"
        class="w-100%"
        :rules="rules"
      >
        <el-form-item label="规章名称" prop="name">
          <el-input
            type="textarea"
            v-model="addEditVisible.data.name"
            class="w-400px"
            placeholder=""
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="addEditClose">取消</el-button>
          <el-button type="primary" @click="addEditSave" :loading="loading">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
    <!--  -->
    <newVersion
      v-if="newVersionData.show"
      :show="newVersionData.show"
      :data="newVersionData.data"
      @close="
        (val, reload) => {
          newVersionData.show = false;
          reload ? getRegulationId() : '';
        }
      "
    ></newVersion>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "RegulationsDetail",
  inheritAttrs: false,
});
import { useRoute, useRouter } from "vue-router";
import {
  ApiGetRegulationId,
  ApiGetRegulation,
  ApiPutRegulationId,
  ApiDelRegulationId,
  ApiPostRegulationActive,
} from "@/api/resource-management/regulations";
import { ApiGetfile } from "@/api/file";
// import { useTagsViewStore } from "@/store";
import { dayjs } from "element-plus";
import newVersion from "./components/newVersion.vue";
import theoryList from "./components/theoryList.vue";
import VuePdfApp from "vue3-pdf-app";
import "vue3-pdf-app/dist/icons/main.css";

const route = useRoute();
const router = useRouter();

const { params, query } = route;

// const tagsViewStore = useTagsViewStore();
// const { visitedViews } = storeToRefs(tagsViewStore);
const loading = ref(false);

const back = () => {
  // tagsViewStore.back();
  router.back();
};

const formData = ref({
  name: "",
  oId: "",
});

const getRegulationId = () => {
  ApiGetRegulationId(query).then((res) => {
    if (res.code == 200) {
      formData.value = res.data;
      getVersion();
    }
  });
};
getRegulationId();

const tableData = reactive({
  data: [],
});
// 拉取版本
const getVersion = () => {
  ApiGetRegulation({
    oId: formData.value.oId,
    skipCount: (page.index - 1) * page.size,
    maxResultCount: page.size,
  }).then((res) => {
    if (res.code == 200) {
      tableData.data = res.data.items.map((e) => {
        return {
          ...e,
          publishTime: dayjs(e.publishTime).format("YYYY-MM-DD"),
        };
      });
      page.total = res.data.totalCount;
    }
  });
};

// 分页
const page = reactive({
  index: 1,
  size: 10,
  total: 0,
});
const pageChange = (val) => {
  page.index = val;
  getVersion();
};

const addEditVisible = reactive({
  type: "rename",
  show: false,
  title: "规章重命名",
  data: {},
});
const RefForm = ref(null);
const rules = reactive({
  name: [{ required: true, message: "规章名称必填", trigger: "change" }],
});
const btnRename = () => {
  addEditVisible.data = JSON.parse(JSON.stringify(formData.value));
  addEditVisible.title = "规章重命名";
  addEditVisible.show = true;
};
const addEditSave = () => {
  RefForm.value.validate((valid, fields) => {
    if (valid) {
      loading.value = true;
      ApiPutRegulationId(addEditVisible.data)
        .then((res) => {
          if (res.code == 200) {
            ElMessage({
              message: `修改成功`,
              type: "success",
            });
            addEditClose();
            getRegulationId();
          }
        })
        .finally(() => {
          loading.value = false;
        });
    }
  });
};
const addEditClose = () => {
  addEditVisible.show = false;
};

// 发布新版
const newVersionData = reactive({
  show: false,
  data: {},
});
const publishNew = () => {
  newVersionData.data = JSON.parse(JSON.stringify(formData.value));
  newVersionData.show = true;
};

// 下载文件
const down = (data) => {
  ApiGetfile({ id: data.file.id }).then((response: any) => {
    const fileData = response.data;
    const fileName = decodeURI(
      response.headers["content-disposition"].split(";")[1].split("=")[1]
    );
    const fileType =
      "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8";

    const blob = new Blob([fileData], { type: fileType });
    const downloadUrl = window.URL.createObjectURL(blob);

    const downloadLink = document.createElement("a");
    downloadLink.href = downloadUrl;
    downloadLink.download = fileName;

    document.body.appendChild(downloadLink);
    downloadLink.click();

    document.body.removeChild(downloadLink);
    window.URL.revokeObjectURL(downloadUrl);
  });
};

// 删除
const del = (data) => {
  ApiDelRegulationId(data).then((res) => {
    if (res.code == 200) {
      ElMessage({
        message: "删除成功！",
        type: "success",
      });
      // if(data.id == formData.value.oId) {}
      getVersion();
    }
  });
};
// 更改状态
const changeState = (data) => {
  ApiPostRegulationActive({ id: data.id, isActive: !data.isActive }).then((res) => {
    if (res.code == 200) {
      ElMessage({
        message: "操作成功！",
        type: "success",
      });
      getVersion();
    }
  });
};

const rightShow = ref(0); // 右侧显示内容，1：文件。2：试题

// 预览pdf,及试题
const pdf = ref("");
const acData = ref({});
const showRight = (data, type) => {
  rightShow.value = type;
  if (type == 1) {
    ApiGetfile({ id: data.file.id }).then((res: any) => {
      const blob = new Blob([res.data], { type: "application/pdf" }); // 保存文件流为 Blob
      pdf.value = URL.createObjectURL(blob); // 转换 Blob 为 URL
    });
  } else if (type == 2) {
    acData.value = data;
    // ApiGetQuestion({ regulationId: data.id }).then((res) => {});
  }
};

const goEdit = () => {
  router.push(route.fullPath.replace("/detail", "/edit"));
};
</script>

<style scope lang="scss">
.border {
  border: 1px solid;
  border-radius: 2px;
}
.app-main-container {
  .title {
    font-family: Source Han Sans CN, Source Han Sans CN;
    font-weight: bold;
    font-size: 16px;
    color: rgba(0, 0, 0, 0.9);
    line-height: 21px;
    text-align: left;
    font-style: normal;
    text-transform: none;
    margin-bottom: 20px;
  }
  .left {
    height: 100%;
    & > .flex {
      background: linear-gradient(180deg, #ffffff 0%, rgba(255, 255, 255, 0.8) 100%);
      border-radius: 20px 20px 20px 20px;
      border: 1px solid rgba(4, 42, 94, 0.1);
    }
    .bg {
      padding: 0 20px;
      background: #eff4ff;
      border-radius: 6px 6px 6px 6px;
    }
    .type {
      background-color: #1759b5;
      font-size: 12px;
      padding: 0 8px;
      border-radius: 6px;
      color: #fff;
    }
    .el-divider {
      &--horizontal {
        margin: 14px 0;
      }
    }
  }
  .right {
    & > .flex-d-col {
      background: linear-gradient(180deg, #ffffff 0%, rgba(255, 255, 255, 0.8) 100%);
      border-radius: 20px 20px 20px 20px;
      border: 1px solid rgba(4, 42, 94, 0.1);
      // padding: 20px;
      overflow: hidden;
    }
  }
}
.example-showcase .el-dropdown-link {
  cursor: pointer;
  color: var(--el-color-primary);
  display: flex;
  align-items: center;
}
.el-button:focus-visible {
  outline: none;
}
</style>
